from django.core.management.base import BaseCommand
from django.utils.text import slugify
from core.models import Category, Document
import os
import markdown
from pathlib import Path

class Command(BaseCommand):
    help = '从指定目录导入文档到对应分类'

    def add_arguments(self, parser):
        parser.add_argument('--path', type=str, default='docs/books/ops', help='相对于项目根目录的文档路径')

    def handle(self, *args, **options):
        # 获取项目根目录（backend的父目录）
        project_root = Path(__file__).resolve().parent.parent.parent.parent.parent
        base_path = os.path.join(project_root, options['path'])
        self.stdout.write(f'开始从 {base_path} 导入文档...')
        
        # 从根目录开始导入
        self.import_directory(base_path, None)
        
        self.stdout.write(self.style.SUCCESS('文档导入完成！'))

    def parse_directory_name(self, dirname):
        """解析目录名称，处理类似 '01_基础设施' 的格式"""
        if '_' in dirname:
            try:
                _, name = dirname.split('_', 1)
                return name
            except ValueError:
                return dirname
        return dirname

    def import_directory(self, dir_path, parent_category):
        # 获取目录名作为分类名
        dir_name = os.path.basename(dir_path)
        
        # 跳过隐藏目录
        if dir_name.startswith('.'):
            return

        # 解析目录名称
        category_name = self.parse_directory_name(dir_name)

        # 查找对应的分类
        if parent_category:
            category = Category.objects.filter(
                parent=parent_category,
                title=category_name
            ).first()
        else:
            # 根分类
            category = Category.objects.filter(parent=None).first()

        if not category:
            self.stdout.write(f'未找到分类: {category_name} (原始目录名: {dir_name})')
            return

        # 处理当前目录下的文档
        for item in os.listdir(dir_path):
            item_path = os.path.join(dir_path, item)
            
            # 如果是目录，递归处理
            if os.path.isdir(item_path):
                self.import_directory(item_path, category)
                continue
            
            # 只处理 markdown 文件
            if not item.endswith('.md'):
                continue
                
            # 读取文档内容
            with open(item_path, 'r', encoding='utf-8') as f:
                content = f.read()
            
            # 如果是 README.md，更新分类描述
            if item.lower() == 'readme.md':
                category.description = content
                category.save()
                self.stdout.write(f'更新分类描述: {category.title}')
                continue
            
            # 解析文档标题（使用文件名作为标题，去除序号前缀）
            file_name = os.path.splitext(item)[0]
            title = self.parse_directory_name(file_name)
            
            # 生成唯一的 slug
            base_slug = slugify(title)
            slug = base_slug
            counter = 1
            while Document.objects.filter(slug=slug).exists():
                slug = f"{base_slug}-{counter}"
                counter += 1
            
            # 创建或更新文档
            doc, created = Document.objects.update_or_create(
                slug=slug,
                defaults={
                    'title': title,
                    'content': content,
                    'category': category,
                }
            )
            
            action = '创建' if created else '更新'
            self.stdout.write(f'{action}文档: {doc.title} (slug: {doc.slug})') 